package com.dhj.yygh.controller.api;

import com.dhj.yygh.common.result.MyResult;
import com.dhj.yygh.service.PayInfoService;
import com.dhj.yygh.service.WeixinService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Map;

@Api(tags = "微信支付相关 api")
@RestController
@RequestMapping("/api/order/weixin")
public class WeiXinController {

    @Autowired
    WeixinService weixinService;

    @Autowired
    PayInfoService payInfoService;

    @ApiOperation("下单生成二维码")
    @GetMapping("/createNative/{orderId}")
    public MyResult<Map<String, Object>> createNative(
            @ApiParam(name = "orderId", value = "订单id", required = true)
            @PathVariable("orderId") Long orderId) {

        Map<String, Object> resultMap = weixinService.createNative(orderId);
        return MyResult.ok(resultMap);
    }

    @ApiOperation("查询支付状态")
    @GetMapping("/getPayStatus/{orderId}")
    public MyResult getPayStatus(
            @PathVariable("orderId") Long orderId) {

        // 支付状态的查询，返回支付状态相关信息的 Map 集合
        Map<String, String> resultMap = weixinService.getPayStatus(orderId);

        if (resultMap == null) {
            return MyResult.fail(201, "支付出错!", null);
        }

        if ("SUCCESS".equals(resultMap.get("trade_state"))) {

            // 更新订单的支付状态
            payInfoService.paySuccess(orderId, resultMap);

            return MyResult.ok(200, "支付成功!", null);
        }

        return MyResult.ok(200, "支付中!", null);
    }
}
